package com.cognizant.ams.common.ldap;

import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class LDAPUtil {
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static boolean  checkAD(String userName,String password ) {
		boolean loginflag=false;
		String host = "10.164.5.1";
		String domain = "alicocorp";
		String port = "389";
//		Properties prop=config.Config.getProperties("ldap");
//        String host=prop.getProperty("ldap.host");//AD域IP
//        String domain =prop.getProperty("ldap.domain");//域名后缀
//        String port =prop.getProperty("ldap.port"); //端口，一般默认389
        String url = new String("ldap://" + host + ":" + port);//固定写法
        String user = domain+"\\"+userName;
        System.out.println("url="+url);
        Hashtable env = new Hashtable();//实例化一个Env
        DirContext ctx = null;
        env.put(Context.SECURITY_AUTHENTICATION, "simple");//LDAP访问安全级别(none,simple,strong),一种模式
        env.put(Context.SECURITY_PRINCIPAL, user); //用户名
        env.put(Context.SECURITY_CREDENTIALS, password);//密码
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");// LDAP工厂类
        env.put(Context.PROVIDER_URL, url);//Url
        try {
            ctx = new InitialDirContext(env);// 初始化上下文
            System.out.println("身份验证成功!");
            loginflag=true;
        } catch (AuthenticationException e) {
            System.out.println("身份验证失败!");
            e.printStackTrace();
        } catch (javax.naming.CommunicationException e) {
            System.out.println("AD域连接失败!");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("身份验证未知异常!");
            e.printStackTrace();
        } finally{
            if(null!=ctx){
                try {
                    ctx.close();
                    ctx=null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return loginflag;
	}
}
